const app = getApp();
const watch = require("../../assets/plugins/watch.js");
const dataFormat = require('../../utils/dataFormat.js');
Page({
  data: {
    inputShowed: true,
    showNoResult: false,
    inputVal: "",
    selectStructure: null,
    showStructure: false,
    showResult: false,
    bridges: [],
  },
  onLoad: function() {
    watch.setWatcher(this); // 设置监听器
    this.setData({
      selectStructure: null,
      token: wx.getStorageSync('openId')
    });
  },
  watch: {
    selectStructure: function(newVal, oldVal) {
      this.searchBridges(newVal);
    }
  },
  showInput: function() {
    this.setData({
      inputShowed: true
    });
  },
  cancelInput: function() {
    wx.navigateBack({
      delta: 1
    });
  },
  selectType: function() {
    this.setData({
      inputShowed: true
    });

    let id = this.data.selectStructure ? this.data.selectStructure.id : '';
    wx.navigateTo({
      url: '/pages/structureType/structureType?id=' + id
    });
  },
  clearInput: function() {
    this.setData({
      inputVal: ""
    });
  },
  searchBridges: function(selectStructure) {
    let searchStr = this.data.inputVal;
    let that = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: app.globalData.siteUrl + '/bridge/searchBridgeList',
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Token": wx.getStorageSync('openId'),
      },
      data: {
        name: searchStr,
        status:1,
        structureTypeId: selectStructure ? selectStructure.id : ''
      },
      success: function(res) {
        let bridges = [];
        if (res.data.model) {
          for (var i = 0; i < res.data.model.length; i++) {
            var newDate = new Date();
            var timestamp = res.data.model[i].createTime;
            let a = dataFormat.tsFormatTime(timestamp, 'Y/M/D');
            res.data.model[i].createTime = a;
            bridges.push(res.data.model[i]);
          }
        }

        that.setData({
          bridges: bridges,
          showResult: true,
          showStructure: true,
          showNoResult: true
        });
      },
      fail: function(e) {
        console.log("查询桥梁错误！");
      },
      complete: function() {
        wx.hideLoading();
      }
    });
  },
  search: function(e) {
    let searchStr = e.detail.value;
    this.setData({
      inputVal: searchStr
    });

    this.searchBridges(this.data.selectStructure);
  },
  selectBridge: function(e) {
    var bridgeId = e.currentTarget.dataset.id;
    let bridges = this.data.bridges;
    let bridgeInfo = bridges.find(function(bridge) {
      return bridge.id === bridgeId;
    });
    wx.navigateTo({
      url: "/pages/show/details/details?bridgeInfo=" + JSON.stringify(bridgeInfo)
    });
  }
});